<template>
  <view class="address-list-page">
    <!-- 地址列表 -->
    <view class="address-list" v-if="addressList.length > 0">
      <view 
        class="address-item"
        v-for="(item, index) in addressList"
        :key="item.id"
        @click="selectAddress(item)"
      >
        <view class="address-info">
          <view class="user-info">
            <text class="name">{{ item.name }}</text>
            <text class="phone">{{ item.phone }}</text>
            <text class="default-tag" v-if="item.isDefault">默认</text>
          </view>
          <view class="address-detail">
            {{ item.province + item.city + item.district + item.detail }}
          </view>
        </view>
        
        <view class="address-action" @click.stop>
          <view class="action-btn edit" @click="editAddress(item)">
            <text class="icon">✎</text>
            <text>编辑</text>
          </view>
          <view class="action-btn delete" @click="confirmDelete(item.id)">
            <text class="icon">×</text>
            <text>删除</text>
          </view>
        </view>
      </view>
    </view>
    
    <!-- 空地址提示 -->
    <view class="empty-address" v-else>
      <image class="empty-image" src="/static/images/empty-address.png"></image>
      <view class="empty-text">您还没有添加收货地址</view>
    </view>
    
    <!-- 添加地址按钮 -->
    <view class="add-address-btn" @click="addAddress">+ 新增收货地址</view>
    
    <!-- 微信收货地址 -->
    <view class="wx-address-btn" @click="getWxAddress">
      <image src="/static/images/icons/wechat.png" class="wx-icon"></image>
      获取微信收货地址
    </view>
  </view>
</template>

<script>
import { mapGetters, mapActions } from 'vuex';
import addressApi from '@/api/address.js';
import '@/styles/pages/address/list.scss';

export default {
  data() {
    return {
      fromCheckout: false // 是否从结算页来的
    };
  },
  computed: {
    ...mapGetters({
      addressList: 'user/addressList'
    })
  },
  onLoad(options) {
    if (options.from === 'checkout') {
      this.fromCheckout = true;
    }
    
    // 获取地址列表
    this.getAddressList();
  },
  methods: {
    ...mapActions({
      getAddressListAction: 'user/getAddressList',
      deleteAddressAction: 'user/deleteAddress',
      setDefaultAddressAction: 'user/setDefaultAddress'
    }),
    
    getAddressList() {
      // 获取收货地址列表
      uni.showLoading({
        title: '加载中...'
      });
      
      addressApi.getAddressList()
        .then(addressList => {
          // 更新Vuex状态
          this.getAddressListAction(addressList);
          uni.hideLoading();
        })
        .catch(error => {
          uni.hideLoading();
          uni.showToast({
            title: '获取地址失败',
            icon: 'none'
          });
        });
    },
    
    addAddress() {
      uni.navigateTo({
        url: '/pages/address/edit'
      });
    },
    
    editAddress(item) {
      uni.navigateTo({
        url: `/pages/address/edit?id=${item.id}`
      });
    },
    
    confirmDelete(id) {
      uni.showModal({
        title: '提示',
        content: '确定要删除该收货地址吗？',
        success: (res) => {
          if (res.confirm) {
            this.deleteAddress(id);
          }
        }
      });
    },
    
    deleteAddress(id) {
      uni.showLoading({
        title: '删除中...'
      });
      
      addressApi.deleteAddress(id)
        .then(() => {
          // 更新Vuex状态
          this.deleteAddressAction(id);
          uni.hideLoading();
          uni.showToast({
            title: '删除成功',
            icon: 'success'
          });
        })
        .catch(() => {
          uni.hideLoading();
          uni.showToast({
            title: '删除失败',
            icon: 'none'
          });
        });
    },
    
    setDefault(id) {
      uni.showLoading({
        title: '设置中...'
      });
      
      addressApi.setDefaultAddress(id)
        .then(() => {
          // 更新Vuex状态
          this.setDefaultAddressAction(id);
          uni.hideLoading();
          uni.showToast({
            title: '设置成功',
            icon: 'success'
          });
        })
        .catch(() => {
          uni.hideLoading();
          uni.showToast({
            title: '设置失败',
            icon: 'none'
          });
        });
    },
    
    selectAddress(address) {
      if (this.fromCheckout) {
        // 如果是从结算页来的，选择地址后返回
        const eventChannel = this.getOpenerEventChannel();
        eventChannel.emit('selectAddress', address);
        uni.navigateBack();
      }
    },
    
    getWxAddress() {
      // 仅在微信小程序有效
      // #ifdef MP-WEIXIN
      uni.chooseAddress({
        success: (res) => {
          // 将微信地址格式转换为本系统格式
          const wxAddress = {
            name: res.userName,
            phone: res.telNumber,
            province: res.provinceName,
            city: res.cityName,
            district: res.countyName,
            detail: res.detailInfo,
            postalCode: res.postalCode,
            isDefault: false
          };
          
          // 导入到系统
          uni.navigateTo({
            url: '/pages/address/edit',
            success: (res) => {
              res.eventChannel.emit('importWxAddress', wxAddress);
            }
          });
        },
        fail: (err) => {
          console.log('获取微信地址失败', err);
          if (err.errMsg !== 'chooseAddress:fail cancel') {
            uni.showToast({
              title: '获取微信地址失败',
              icon: 'none'
            });
          }
        }
      });
      // #endif
      
      // 非微信小程序
      // #ifndef MP-WEIXIN
      uni.showToast({
        title: '此功能仅支持微信小程序',
        icon: 'none'
      });
      // #endif
    }
  }
};
</script> 